package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.exception.LoginException;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendCode(String phone, HttpSession session) {
        //1·校验手机号是否正确
        System.out.println(phone);
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            throw new LoginException("手机号格式不正确");
        }
        //2.生成验证码
        String code = UUID.randomUUID().toString().substring(0, 6);

        //3.保存到seesion中去
        session.setAttribute(phone, code);  //保存到session中去
        //4.发送验证码短信
        System.out.println("验证码：" + code);
    }

    @Override
    public void login(LoginFormDTO loginForm, HttpSession session) {
        //首先校验手机号
        String phone = loginForm.getPhone();
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            throw new LoginException("手机号格式不正确");
        }
        //然后校验验证码
        String code = (String) session.getAttribute(phone);
        if (code == null) {
            throw new LoginException("验证码已过期");
        }
        if (!loginForm.getCode().equals(code)) {
            throw new LoginException("验证码错误");
        }
        //验证码正确，登录成功
        User user = userMapper.selectByPhone(phone);
        if (user == null) {
            //用户不存在，需要注册
            user = createUserWithPhone(phone);
            userMapper.insert(user);
        }
        //登录成功，保存用户信息到session中
        session.setAttribute("user", user);  //保存到session中去
    }

    private User createUserWithPhone(String phone) {
        User user = User.builder()
                .phone(phone)
                .nickName("user")
                .build();
        return user;
    }
}
